<?php
/**
 * Created by PhpStorm.
 * User: sky
 * Date: 2019/7/16
 * Time: 23:04
 */

namespace App\Repositories;

use App\Models\GoodsAttributes;
use App\Models\GoodsAttributesValue;
use App\Models\GoodsType;
use Illuminate\Support\Facades\DB;

class GoodsTypeRepositories
{
    public function model()
    {
        return GoodsType::query();
    }

    public function find($id)
    {
        return $this->model()->with(['manyParams','manyAttributes'])->where('id',$id)->first();
    }

    public function save($data)
    {
        return $this->model()->create($data);

    }
    public function update($id,$data)
    {
        $updateData=[
            'name'=>$data['name'],

        ];
        return $this->model()->where('id',$id)->update($updateData);
    }

    public function search($data)
    {
        $model = $this->model()->with(['manyParams','manyAttributes']);

        if(isset($data['name']))
        {
            $model = $model->where('name','like','%'.$data['name'].'%');
        }

        //些处扩展更多查询条件
        return $model->orderBy('created_at','desc')->paginate($data['limit'])->toArray();
    }

    public function delete($ids)
    {
        DB::beginTransaction();
        try
        {
            $res =GoodsType::destroy($ids);
            GoodsType::whereIn('attribute_id', $ids)->delete();
            DB::commit();
            return $res;
        }
        catch (\Exception $exception)
        {
            DB::rollBack();
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * @param $typeId
     * @param $paramsId
     * @return mixed
     * 分配参数绑定到类型
     * 用于关联的 新增 更新操作sync
     */
    public function assignParams($typeId,$paramsId)
    {
        $type =$this->model()->with(['manyParams'])->findOrFail($typeId);
        return $type->manyParams()->sync($paramsId);
    }

    public function assignAttributes($typeId,$attributesId)
    {
        $type =$this->model()->with(['manyAttributes'])->findOrFail($typeId);
        return $type->manyAttributes()->sync($attributesId);
    }

    public function allGoodsType()
    {
        return $this->model()->get()->toArray();
    }
}